package com.example.lvsuo.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.example.lvsuo.modal.Constant;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Map;

public class JwtUtils {
    /**
     * 创建token
     * @param user
     * @param role
     * @return
     */
    public static String createToken(String user,String role){
        LocalDateTime plus = LocalDateTime.now().plus(120, ChronoUnit.MINUTES);//过期时间：30分钟
        Instant instant = plus.atZone(ZoneId.systemDefault()).toInstant();
        Date from = Date.from(instant);

        return JWT.create().withSubject(user)
                .withClaim("user",user)
                .withClaim("role",role)
                .withExpiresAt(from)
                .sign(Algorithm.HMAC384(Constant.SECRET.getValue()));
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public static Map<String, Claim> check(String token){
        JWTVerifier verifier = JWT.require(Algorithm.HMAC384(Constant.SECRET.getValue())).build();
        return verifier.verify(token).getClaims();
    }
}
